import { defineStore } from "pinia";
import { ref } from 'vue'
import request from '@/utils/request'
import { ElMessage } from "element-plus";
export const useMenuStore = defineStore('MenuStore', () => {
    const menuSearch = ref({name:''})
    const pageInfo = ref({ current: 1, pageSize: 5, total: 0 })
    const menus = ref([])
    const ids = ref([])
    const updateDialogVisible = ref(false)
    const menuFrom = ref({})
    const menuDialogVisible = ref(false)
    const menuData = ref([])
    const menuIcons = ref([])
    const menuIconsList = ['House','Management','User','Folder','Avatar','Menu','Setting','InfoFilled']
    const getMenus = async () => {
        const {data} = await request.get('/menu', {
            params: {
                name: menuSearch.value.name
            }
        })
        menus.value = data
    }
    const getMenuIcons = async () =>{
        menuIconsList.forEach(item => menuIcons.value.push({label: item,value: item}))
        console.log(menuIcons.value)
    }
    const save = async () => {
        const result = await request.post('/menu', menuFrom.value)
        if (result.code === 200) {
            ElMessage.success('保存成功')
            updateDialogVisible.value = false
            getMenus()
        }else {
            ElMessage.warning(result.msg)
        } 
    }
    const refresh = () => {
        menuSearch.value = { name: '' }
        getMenus()
    }
    const deleteMenu = async (id) => {
        const result = await request.delete(`/menu/${id}`)
        result.code === 200 ? ElMessage.success('保存成功') : ElMessage.warning(result.msg)
        getMenus()
    }
    const deleteMenus = async () => {
        const result = await request.delete('/menu', {
            data: ids.value
        })
        result.code && result.code === 200 ? ElMessage.success('删除成功') : ElMessage.warning(result.msg)
        getMenus()
    }
    const handleSelectionChange = (val) => {
        ids.value = val.map(item => item.id)
    }
    const EditMenu = (row)=>{
        menuFrom.value = row
        getMenuIcons()
        updateDialogVisible.value =true
    }
    const addChildrenMenu = (row)=>{
        menuFrom.value = {}
        menuFrom.value.pid = row.id 
        menuDialogVisible.value = true
    }
    

    return {
        menus,
        menuSearch,
        pageInfo,
        updateDialogVisible,
        menuFrom,
        menuData,
        menuDialogVisible,
        menuIcons,
        getMenus,
        save,
        deleteMenu,
        refresh,
        deleteMenus,
        EditMenu,
        handleSelectionChange,
        addChildrenMenu
    }
})